package com.lwz.educenter.controller;

import com.lwz.educenter.entity.UcenterMember;
import com.lwz.educenter.entity.Vo.RegisterVo;
import com.lwz.educenter.service.UcenterMemberService;
import com.lwz.servicebase.exceptionhandler.MyException;
import com.lwz.util.JwtInfo;
import com.lwz.util.JwtUtil;
import com.lwz.util.R;
import com.lwz.util.orderVo.UcenterMemberOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author Lw中
 * @since 2020-11-18
 */
@RestController
@RequestMapping("/educenter/member")
@CrossOrigin
public class UcenterMemberController {

    @Autowired
    UcenterMemberService ucenterMemberService;

    /**
     * LWZ TODO : 2020/11/19  SSO(single sign on)单点登录模式
     */

    /**
     * 登录接口
     * @param ucenterMember
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UcenterMember ucenterMember) {
        // ucenterMember用于存储用户的手机号和密码
        String token = ucenterMemberService.login(ucenterMember);
        return R.ok().data("token", token);
    }

    /**
     * 注册接口
     * @param registerVo
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo) {
        ucenterMemberService.register(registerVo);
        return R.ok();
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {
        try {
            //调用jwt工具类的方法。根据request对象获取头信息，返回用户id
            JwtInfo jwtInfo = JwtUtil.getMemberIdByJwtToken(request);
            return R.ok().data("userInfo", jwtInfo);
        } catch (Exception e) {
            throw new MyException(20001, "查询出错");
        }
    }

    /**
     * 根据用户id获取用户的信息
     * @param id
     * @return
     */
    @PostMapping("/getUserInfo/{id}")
    public UcenterMemberOrder getUserInfo(@PathVariable String id) {
        UcenterMember ucenterMember = ucenterMemberService.getById(id);
        UcenterMemberOrder ucenterMemberOrder = new UcenterMemberOrder();
        // 将ucenter赋值给ucenterMember
        BeanUtils.copyProperties(ucenterMember, ucenterMemberOrder);
        return ucenterMemberOrder;
    }

    /**
     * 查询一天注册人数
     * @param day
     * @return
     */
    @GetMapping("/countRegister/{day}")
    public int countRegister(@PathVariable String day) {
        int count = ucenterMemberService.countRegisterDay(day);
        return count;
    }

}

